/**
 * Created by lixiaodi on 2019/06/06 0027.
 */
mini.parse();

var grid = mini.get('datagrid1');
var sendPeopleNameEl = mini.get('sendPeopleName');	//发件人元素
var searchForm = new mini.Form("searchFormBar");	//搜索栏目
var url = bootPATH + "../frame/frame1/pages/";      //路径前缀
var mailDataLocal = localStorage.getItem("mailData");
var pager = grid.getBottomPager();					//分页
var stateSql = '';										//查询信息列表(带状态)sql
//页面初始化
$(function (){
	//stateSql = " and status = status";	//全部信息
	httpRequest('0','');
})
//表格的操作按钮绘制
function onActionRenderer(e) {
    var grid = e.sender;
    var record = e.record;
    var uid = record._uid;
    var rowIndex = e.rowIndex;
    var s = ' <a class="mini-button Edit_Button" href="javascript:onSee(\'' + uid + '\')" >查看</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onReply(\'' + uid + '\')" >再次发送</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onDelete(\'' + uid + '\')" >删除</a>';
    return s;
}
//选择发件人
function changePerson(){
	mini.open({
        url: bootPATH + "../frame/frame1/pages/booking/Mail/changePerson.html",
        title: "选择发件人",
        width: 600,
        height: 400,
        ondestroy: function (action) {
            //if (action == "close") return false;
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.GetData();
                data = mini.clone(data);    //必须
                //赋值
                sendPeopleNameEl.setValue(data.operatorId);
                sendPeopleNameEl.setText(data.perName);
            }
        }
    });
}
//根据条件查询
function onSearch(){
	//得到查询条件数据
	searchData = searchForm.getData();
	//拼接查询sql
	var dataStr = stateSql;       //存放sql
	//通过name得到日期区间得元素并且得到用户填写得值
    var colum1 = mini.getByName('push_time').getValue();
    var colum2 = mini.getByName('push_time2').getValue();
    //如果值都不为空，那么执行sql语句
    if(colum1 != "" && colum2 != ""){
        if(tab(colum1,colum2)){
            colum1 = mini.formatDate(colum1,"yyyy-MM-dd");       //时间格式
            colum2 = mini.formatDate(colum2,"yyyy-MM-dd");       //时间格式
            dataStr += " and " + 'push_time' + " between '" + colum1 + "' and " + "'" + colum2 + "'";
        }else{
            mini.alert("第二个日期不能大于以一个日期");
        }
    }else if(colum1 == "" && colum2 != ""){
        colum2 = mini.formatDate(colum2,"yyyy-MM-dd");       //时间格式
        dataStr += " and push_time" + " <= " + "'" + colum2 + "'";
    }else if(colum1 != "" && colum2 == ""){
        colum1 = mini.formatDate(colum1,"yyyy-MM-dd");       //时间格式
        dataStr += " and push_time" + " >= " + "'" + colum1 + "'";
    }
    //删除时间字段
    delete searchData.push_time;
    delete searchData.push_time2;
    //除时间以外的sql拼接
    for(var key in searchData){
    	if(searchData[key]){
    		if(key == 'book_isbn'){
    			dataStr += " and "  + key + " in (" + searchData[key] + ")";
    		}else if(key == 'send_peopleName'){
    			dataStr += " and send_people like '%" + searchData[key] + "%'";
    		}else{
    			dataStr += " and "  + key + " like '%" + searchData[key] + "%'";
    		}
    	}
    }
    var searchSql = dataStr;
	//查询数据
	httpRequest('0',searchSql);
}
//新增
function onInfo(state,row){
	if(mailDataLocal){
		localStorage.removeItem('mailData');
	}
	switch (state) {
	case 'new': 
		onJump('新增邮件')
		break;
	case 'edit':
		if(row){
			//row.types = '新增';
			console.log(row,'如果不是新增时');
			//将需要编辑的数据带过去
			localStorage.setItem("mailData",JSON.stringify(row));
			onJump('编辑邮件');
		}else{
			mini.alert('请选择需要编辑的邮件');
		}
		break;
}
}

//查看邮件
function onSee(row_uid){
	var row = grid.getRowByUID(row_uid);
	if(row){
		row.types = 'outbox';
		localStorage.setItem('seeMailInfo',JSON.stringify(row));
		var item = {
	        iconCls: "fa fa-desktop",
	        text: "信息正文",
	        url: "../pages/booking/Mail/msgInfo.html"
	    };
	    parent.activeTab(item);//与父页面通信
	}
}
//再次转发(onclick="onInfo('edit')")
function onReply(row_uid){
	//清缓存
	if(mailDataLocal){
		localStorage.removeItem('mailData');
	}
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	if(row){
		row.types = '再次发送';
		onInfo('edit',row);
	}
}
//删除(单条)
function onDelete(row_uid){
	//根据uid获取行数据
	var row = grid.getRowByUID(row_uid);
	if(row){
		mini.confirm('是否删除选中信息','系统提示',function(action){
			if(action == 'ok'){
				//row.status = row.status == '未读' ? 0 : 1;
				var msgObj = {
						entityName: 'MessageInfo',
						msg_info_id: row.msg_info_id,
						msg_text: row.msg_text,
						msg_title: row.msg_title,
						appendix: '',
						is_del: 1,
						old_msg: row.old_msg,
						push_time: row.push_time,
						ready_code: row.ready_code,
						user_id: row.user_id,
						send_people: row.send_people,
						
				};
				var msgStr = JSON.stringify(msgObj);
				$.ajax({
					url: ajaxUrl + '/msg/updateSendIsDel.do?',
					type: 'POST',
					data: msgStr,
		            contentType : "application/json",
					success: function(data){
						showTips(data.data);
						httpRequest();
					},
					error: function(msg){
						console.log(msg);
						mini.alert('请求失败');
					}
				});
			}
		})
	}
}
//删除(多条)
function onRemove(){
	 var rows = grid.getSelecteds();
	 if (rows.length > 0) {
	        mini.confirm("确定删除选中记录？","系统提示",function(action){
	            if(action == "ok"){
	                var ids = [];
	                for (var i = 0, l = rows.length; i < l; i++) {
	                    var r = rows[i];
	                    ids.push(r.msg_info_id);
	                }
	                var id = ids.join(',');
	                grid.loading("操作中，请稍后......");
	                $.ajax({
	                    url: ajaxUrl + "/msg/updateSendIsDels.do?ids=" + id,
	                    type:"post",
	                    success: function (data) {
	                    	grid.unmask();
	                        if(data.status == 200){
	                        	showTips(data.data);
	                        	httpRequest();
	                        }else{
	                        	mini.alert(data.data);
	                        }
	                    },
	                    error: function () {
	                        mini.alert('失败');
	                    }
	                });
	            }
	        });
	    } else {
	        mini.alert("请选中一条记录");
	    }
}

//跳转函数
function onJump(text){
	//跳转
	var item = {
		id: text,
	    iconCls: "fa fa-desktop",
	    text: text,
	    url: "../pages/booking/Mail/mAddAndEdit.html"
	};
	//var data = parent.allTabs();
	//console.log(data);
	parent.activeTab(item);//与父页面通信
}
//刷新
function onRefresh(){
	//stateSql = " and status = status";	//全部信息
	httpRequest('0','');
}
//发件list请求
function httpRequest(pageIndex,paramSql){
	var pageObj = {
			pageSize: '500',
			pageNum: pageIndex,
			paramSql: paramSql
	}
	var pageStr = JSON.stringify(pageObj);
	$.ajax({
		url: ajaxUrl + '/msg/msgOutList.do',
		type: 'POST',
		data: pageStr,
		contentType : "application/json",
		success: function(data){
			if(data.status == 706){
				showTips(data.data);
			}else if(data.status == 200){
				var mailList = data.data;
				mailList.forEach((item)=>{
					item.userNames = item.userNames.substring(0,item.userNames.length-1);
					item.status = item.status == '1' ? '发送成功' : '发送失败';
					if(item.push_time){
						item.push_time = formatDateSec(item.push_time);
					}else{
						item.push_time = '';
					}
				});
				grid.setData(mailList);
				pager.set({"totalCount":data.count.count});        //设置分页总数
			}else if(data.status == 601){
				//提示登陆超时
				mini.alert(data.data,'系统提示',function (action){
					if(action == 'ok'){
						//跳转至登陆页面
						window.location.href = "/bpm/ToLogin.do";
					}
				});
				
			}else{
				mini.alert(data.data);
			}
			
		},
		error: function(msg){
			console.log(msg);
			mini.alert('请求失败');
		}
	});
}
//提示信息
function showTips(text) {
    mini.showTips({
        content: "<b>" + text + "</b>",
        state: "success",
        x: "center",
        y: "center",
        timeout: 2000
    });
}
////新增
//function onAdd1(){
//	mini.open({
//        url: url + "booking/Mail/mAddAndEdit.html",
//        title: "新增邮件", width: 600, height: 400,
//        onload: function () {
//            var iframe = this.getIFrameEl();
//            var data = { action: "new"};
//            iframe.contentWindow.SetData(data);
//        },
//        ondestroy: function (action) {
//        	httpRequest();
//        }
//    });
//}
////编辑
//function edit() {
//    var row = grid.getSelected();
//    if (row) {
//        mini.open({
//            url: url + "booking/Mail/mAddAndEdit.html",
//            title: "编辑邮件", width: 600, height: 400,
//            onload: function () {
//                var iframe = this.getIFrameEl();
//                var data = { action: "edit", id: row };
//                iframe.contentWindow.SetData(data);
//            },
//            ondestroy: function (action) {
//            	httpRequest();
//            }
//        });
//
//    } else {
//        mini.alert("请选中一条记录");
//    }
//
//}